package com.basin.common.glc.func;

import cn.hutool.core.lang.UUID;
import com.basin.common.glc.context.BasinLogContext;
import com.basin.common.glc.pojo.BasinLogVO;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 * @date: 2025/6/21 18:28
 * @description:
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        BasinLogVO parentLog = BasinLogContext.get();

        // 创建子日志对象
        BasinLogVO childLog = new BasinLogVO();
        childLog.setTraceId(parentLog.getTraceId());
        childLog.setLogId(UUID.fastUUID().toString(true));
        childLog.setStartTime(System.currentTimeMillis());
        childLog.setRequestUri(template.url());

        // 记录请求参数（Feign参数需要特殊处理）
        Map<String, Collection<String>> queries = template.queries();
        if (!queries.isEmpty()) {
            Map<String, String> params = new HashMap<>();
            queries.forEach((k, v) -> params.put(k, v.iterator().next()));
            childLog.setParams(params);
        }

        // 记录请求头
        Map<String, Collection<String>> headers = template.headers();
        if (!headers.isEmpty()) {
            Map<String, String> headerMap = new HashMap<>();
            headers.forEach((k, v) -> headerMap.put(k, String.join(",", v)));
            childLog.setHeaders(headerMap);
        }

        // 将子日志存入父日志的调用链
        parentLog.getTraces().add(childLog);
    }
}
